package com.ai_chat.common.util;

import com.alibaba.fastjson2.JSON;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.security.PrivateKey;
import java.security.PublicKey;
import java.util.Date;
import java.util.UUID;

@Component
public class JwtUtil {
    private static final long JWT_EXPIRE = 60*60*1000L;//1小时

    @Autowired
    private RSA256Util rsa256Util;

    public String createToken(Object data){
        long currentTime = System.currentTimeMillis();
        long expireTime = currentTime + JWT_EXPIRE;

        PrivateKey privateKey = rsa256Util.getPrivateKey();
        JwtBuilder builder = Jwts.builder()
                .setId(String.valueOf(UUID.randomUUID()))
                .setSubject(JSON.toJSONString(data))
                .setIssuer("ai_chat")
                .setIssuedAt(new Date(currentTime))
                .signWith(SignatureAlgorithm.RS256,privateKey)
                .setExpiration(new Date(expireTime));

        return builder.compact();
    }

    public Claims parseToken(String token){
        PublicKey publicKey = rsa256Util.getPublicKey();
        Claims body = Jwts.parser()
                .setSigningKey(publicKey)
                .parseClaimsJws(token)
                .getBody();
        return body;
    }
    public <T> T parseToken(String token, Class<T> clazz){
        PublicKey publicKey = rsa256Util.getPublicKey();

        Claims body = Jwts.parser()
                .setSigningKey(publicKey)
                .parseClaimsJws(token)
                .getBody();
        return JSON.parseObject(body.getSubject(),clazz);
    }
}
